package cn.yomigaeri.gateway.filters;

import cn.yomigaeri.gateway.config.AuthProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName: AuthGiobalFilter
 * @Package: cn.yomigaeri.gateway.filters
 * @Description:
 * @Author 王璇
 * @Create 2025/5/10 17:28
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        log.info("Request path: {}", path);

        if (isExclude(path)) {
            log.info("Path {} is excluded, allowing request", path);
            return chain.filter(exchange);
        }

        log.info("Path {} requires authentication, processing...", path);
        // 添加你的认证逻辑

        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (path.contains(excludePath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
